package com.chenyq.rabbitmq.publish_subscribe;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 *
 * @author chenyq
 * @date 2023/11/29
 */

public class Producer {
    //几个常量
    private static final String FANOUT_EXCHANGE = "fanoutExchange";
    private static final String FANOUT_QUEUE_1 = "fanoutQueue1";
    private static final String FANOUT_QUEUE_2 = "fanoutQueue2";

    public static void main(String[] args) {

        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置主机地址
        factory.setHost("127.0.0.1");
        // 设置端口号
        factory.setPort(5672);
        // 设置虚拟主机
        factory.setVirtualHost("/");
        // 设置用户名
        factory.setUsername("admin");
        // 设置密码
        factory.setPassword("123456");

        // 创建连接
        Connection connection = null;
        // 创建通道
        Channel channel = null;
        try {
            // 创建连接
            connection = factory.newConnection();
            // 创建通道
            channel = connection.createChannel();
            //声明交换机
            channel.exchangeDeclare(FANOUT_EXCHANGE, BuiltinExchangeType.FANOUT,true,false,null);
            // 声明队列
            channel.queueDeclare(FANOUT_QUEUE_1, true, false, false, null);
            channel.queueDeclare(FANOUT_QUEUE_2, true, false, false, null);

            //队列和交换机的相互绑定
            channel.queueBind(FANOUT_QUEUE_1,FANOUT_EXCHANGE,"");
            channel.queueBind(FANOUT_QUEUE_2,FANOUT_EXCHANGE,"");

                String msg = "你在拼多多购买的商品已下单,请及时付款";
                // 发布消息
                channel.basicPublish(FANOUT_EXCHANGE,"",null,msg.getBytes());

        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                // 关闭通道
                if (channel != null & connection != null) {
                    channel.close();
                    connection.close();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }

    }

}
